package neublaController

import (
	"errors"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"

	"tupu-go/pkg/res"
	"tupu-go/service/buildSchema"

	"github.com/gin-gonic/gin"
)

type ImportController struct{}

// ImportData 数据导入接口
func (ic *ImportController) ImportData(c *gin.Context) {
	// 获取上传的文件
	yamlFile, yamlHeader, err := c.Request.FormFile("yaml_file")
	if err != nil {
		res.ErrorResponse(c, http.StatusInternalServerError, errors.New("yaml文件上传失败"))
		return
	}
	defer yamlFile.Close()

	dataFile, dataHeader, err := c.Request.FormFile("data_file")
	if err != nil {
		res.ErrorResponse(c, http.StatusInternalServerError, errors.New("data_file文件上传失败"))
		return
	}
	defer dataFile.Close()

	// 验证文件类型
	if !isValidYAMLFile(yamlHeader.Filename) {
		res.ErrorResponse(c, http.StatusInternalServerError, errors.New(" 请上传有效的YAML配置文件"))
		return
	}

	if !isValidDataFile(dataHeader.Filename) {
		res.ErrorResponse(c, http.StatusInternalServerError, errors.New(" 请上传有效的CSV或Excel数据文件"))
		return
	}

	// 创建临时目录
	tempDir := fmt.Sprintf("config/temp/import_%d", time.Now().Unix())
	if err := os.MkdirAll(tempDir, 0755); err != nil {
		res.ErrorResponse(c, http.StatusInternalServerError, errors.New(" 创建临时目录失败"))
		return
	}
	defer os.RemoveAll(tempDir) // 清理临时文件

	// 保存YAML配置文件
	yamlPath := filepath.Join(tempDir, "config.yaml")
	if err := saveUploadedFile(yamlFile, yamlPath); err != nil {
		res.ErrorResponse(c, http.StatusInternalServerError, errors.New(" 保存YAML文件失败"))
		return
	}

	// 处理数据文件
	dataPath := filepath.Join(tempDir, "data.csv")
	if strings.HasSuffix(strings.ToLower(dataHeader.Filename), ".xlsx") {
		// Excel转CSV
		if err := convertExcelToCSV(dataFile, dataPath); err != nil {
			res.ErrorResponse(c, http.StatusInternalServerError, errors.New(" excel文件转换失败"))
			return
		}
	} else {
		// 直接保存CSV文件
		if err := saveUploadedFile(dataFile, dataPath); err != nil {
			res.ErrorResponse(c, http.StatusInternalServerError, errors.New(" csv文件保存失败"))
			return
		}
	}

	// 执行数据导入
	result, err := buildSchema.ExecuteImport(yamlPath, dataPath)
	if err != nil {
		res.ErrorResponse(c, http.StatusInternalServerError, errors.New("导入失败"))
		return
	}

	res.SuccessResponse(c, result)
}

// 验证YAML文件
func isValidYAMLFile(filename string) bool {
	lower := strings.ToLower(filename)
	return strings.HasSuffix(lower, ".yaml") || strings.HasSuffix(lower, ".yml")
}

// 验证数据文件
func isValidDataFile(filename string) bool {
	lower := strings.ToLower(filename)
	return strings.HasSuffix(lower, ".csv") || strings.HasSuffix(lower, ".xlsx")
}

// 保存上传的文件
func saveUploadedFile(file multipart.File, dst string) error {
	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, file)
	return err
}
